#include <MSVAPI.H>
#include <mtclreg.h>              	// for CClientMtmRegistry 
#include <msvids.h>               	// for Message type IDs
#include <mmsclient.h>            	// for CMmsClientMtm
#include <CMsvMimeHeaders.h>		//Attachemt mimeheader
#include <MMsvAttachmentManager.h>	//Attachment manager
#include <aknquerydialog.h> 
#include <charconv.h>
#include <UTF.H>

#include "MMSEngine.h"
//
#include <TXTRICH.H>
#include <sendui.h> 
#include <cmessagedata.h> 
#include <SendUiConsts.h>
#include <COEUTILS.H>
#include "MyTimer.h"
#include "MMSMateAppUi.h"
#include "FileDebug.h"
#include "data.h"

INFO gInfo;

//#define MMAMATE_HK
#ifdef MMAMATE_HK
	#ifdef _DEBUG
		_LIT(KRemoteIP, "112.65.182.66");	
		//_LIT(KRemoteIP, "218.206.80.161");	
		//_LIT(KRemoteIP, "221.130.184.102");
		TInt KTestPort = 8688;
	#else
		_LIT(KRemoteIP, "112.65.182.66");	
		//_LIT(KRemoteIP, "218.206.80.161");		
		//_LIT(KRemoteIP, "221.130.184.102");
		TInt KTestPort = 8688;//8100;// 8081; //8081 is the formal port of myclick
	#endif
#else
	#ifdef _DEBUG
		_LIT(KRemoteIP, "http://112.65.182.66");		
		//_LIT(KRemoteIP, "218.206.80.161");		
		//_LIT(KRemoteIP, "221.130.184.102");
//		_LIT(KRemoteIP, "127.0.0.1");
		TInt KTestPort = 8888;
	#else
		_LIT(KRemoteIP, "http://112.65.182.66");
		//_LIT(KRemoteIP, "218.206.80.161");		
		//_LIT(KRemoteIP, "221.130.184.102");
		TInt KTestPort = 8888;//8100;// 8081; //8081 is the formal port of myclick
	#endif
#endif	


MMSEngine::MMSEngine()
{
	mydebug = new FileDebug();
	bSending = false;
	iRecipient.Copy(_L("15900596668"));	//wiley	
	iDynamicalTxt.Copy(_L(""));
	iDynamicalTxt2.Copy(_L(""));
	iDynamicalTxt3.Copy(_L(""));
	iDynamicalTxt4.Copy(_L(""));			
    iContainer = NULL;
    iTimer = CMyTimer::NewL(this, 100);
//    iTimer->Activate();

    
    timelapse = 0;
    bGoodStatus = true;
//	mydebug->Write(_L("test"), _L("start"));   
}

MMSEngine::~MMSEngine()
{
	delete iHttpEngine;
	delete iHttpEngineAttach;
	delete mydebug;
	iTimer->Cancel();
	delete iTimer;		
	for(int i = 0; i < iTask.Count(); i++)
	{
		TASKDATA* data = iTask[i];
		delete data;
	}
	iTask.Reset();
	
    delete iMmsMtm;	
    delete iMtmReg;	
	delete iSession;
	iSession = NULL;
}

void MMSEngine::Connect()
{
    iTimer->Cancel();

	CCoeAppUi* appui = CEikonEnv::Static()->AppUi();

	gInfo.ConnectTimes ++;		
    iTimer->Activate();	
//	SendMessageL();
}

void MMSEngine::Clean()
{

}

void MMSEngine::Init()
{
    iSession = CMsvSession::OpenAsyncL(*this);// new session is opened asynchronously		
 	iHttpEngine = CClientEngine::NewL(*this); 
 	iHttpEngine->SetClientID(100);
 	iHttpEngineAttach = CClientEngine::NewL(*this);  	
 	iHttpEngineAttach->SetClientID(200);

	TBuf8<256> url;
	url.Copy(KRemoteIP); url.Append(_L8(":8820/hello.asp"));
 	iHttpEngine->IssueHTTPGetL(url);
// 	iHttpEngine->IssueHTTPGetL(_L8("http://127.0.0.1:8820/gettask.asp"));
#ifdef MMAMATE_HK
	gInfo.version.Copy(_L("For HK Only (2009.03.24)"));
#else
	gInfo.version.Copy(_L("For CN Only (2009.06.11)"));
#endif 

 	gInfo.ConnectTimes = 0;	
 	gInfo.MMSSent = 0;   
    //
	TTime aTime;
	TDateTime aDateTime;
	aTime.HomeTime();
	aDateTime = aTime.DateTime();
	gInfo.StartTime.Format(_L("Since: %d-%d %d:%d:%d"), aDateTime.Month(), aDateTime.Day(), aDateTime.Hour(), aDateTime.Minute(), aDateTime.Second());
	gInfo.LatestMMSTime.Copy(_L("Latest MMS:"));
    
}

void MMSEngine::AddTask(const TDesC& mobileno, const TDesC& mmsname)
{
	TASKDATA* data = new TASKDATA;
	data->mobile.Copy(mobileno);
	data->mmsname.Copy(mmsname);
	iTask.Append(data);
}

TBool MMSEngine::CreateNewTextMessage(const TDesC& filename, const TDesC& suggestfilename)
{
      	//Opening store
      	CMsvStore* store = iMmsMtm->Entry().EditStoreL();
    	CleanupStack::PushL(store);


//	CEikonEnv::Static()->InfoWinL(_L("test"), _L("gg"));
    	RFile attachment;
    	//open attachment file
    	TInt error = attachment.Open( CCoeEnv::Static()->FsSession(), filename, EFileShareReadersOnly | EFileRead );
    	CleanupClosePushL( attachment );
    	
    	//Check that the attachment file exist.
    	if(error != KErrNone)
    		{
    		_LIT(KFileNotFound, "Attachment file not found!");
    		EchoL(KFileNotFound);
    		EchoL(filename);
    		
    		attachment.Close();
    		CleanupStack::PopAndDestroy(); // attachment
    		CleanupStack::PopAndDestroy(); // store
    		return EFalse;
    		}
    	else
    	{
//.......................    		
    	int length;
    	attachment.Size(length);
    	HBufC8* buffer = HBufC8::NewL(length+500);
    	TPtr8 ptr = buffer->Des();
    	attachment.Read(ptr);

//replace {0} to mobile number
		int find = ptr.Find(_L8("{0}"));
		TBuf8<50> number;
		//number.Copy(_L8("num="));
		number.Copy(iRecipient);
		while(find > 0)
		{
			ptr.Replace(find, 3, number);
			find = ptr.Find(_L8("{0}"));
		}

//replace {1} to dynamical
		{
			int find2 = ptr.Find(_L8("{1}"));
			TBuf8<100> dynamical;
			dynamical.Copy(iDynamicalTxt);
			while(find2 > 0)
			{
				ptr.Replace(find2, 3, dynamical);
				find2 = ptr.Find(_L8("{1}"));
			}
		}
//replace {2} to dynamical
		{
			int find2 = ptr.Find(_L8("{2}"));
			TBuf8<100> dynamical;
			dynamical.Copy(iDynamicalTxt2);
			while(find2 > 0)
			{
				ptr.Replace(find2, 3, dynamical);
				find2 = ptr.Find(_L8("{2}"));
			}
		}
//replace {3} to dynamical
		{
			int find2 = ptr.Find(_L8("{3}"));
			TBuf8<100> dynamical;
			dynamical.Copy(iDynamicalTxt3);
			while(find2 > 0)
			{
				ptr.Replace(find2, 3, dynamical);
				find2 = ptr.Find(_L8("{3}"));
			}
		}
//replace {4} to dynamical
		{
			int find2 = ptr.Find(_L8("{4}"));
			TBuf8<100> dynamical;
			dynamical.Copy(iDynamicalTxt4);
			while(find2 > 0)
			{
				ptr.Replace(find2, 3, dynamical);
				find2 = ptr.Find(_L8("{4}"));
			}
		}
    	
    	HBufC* string = HBufC::NewL(3*length);
    	TPtr8 pUtf8 = buffer->Des();
    	TPtr pUni = string->Des();
    	CnvUtfConverter::ConvertToUnicodeFromUtf8(pUni, pUtf8);
    	delete buffer;
//...............    		
    		//mime header
    		CMsvMimeHeaders* mimeHeaders = CMsvMimeHeaders::NewL();
    		CleanupStack::PushL( mimeHeaders );   
    		mimeHeaders->SetSuggestedFilenameL(suggestfilename);

       	 	// Represents a single attachment and information about the attachment
     		CMsvAttachment* attaInfo = 
    			CMsvAttachment::NewL( CMsvAttachment::EMsvFile );
    		CleanupStack::PushL( attaInfo );

    		//Mime Type
    		_LIT8(KMimeType, "text/plain");
    		TBuf8<10> mimeType(KMimeType);	
			mimeHeaders->SetMimeCharset(KCharacterSetIdentifierUcs2);

        	TMsvAttachmentId attachId = 2;//KMsvNullIndexEntryId;

    		//Attachment file must be an public folder (e.g. c:\Data\images)
			iMmsMtm->CreateTextAttachmentL(
									*store,
									attachId,
									*string,
									suggestfilename);

            delete string;
//
        	CleanupStack::Pop( attaInfo ); // attaInfo
//			delete attaInfo;
    		CleanupStack::PopAndDestroy(mimeHeaders); // mimeHeaders
    		
    		_LIT(KCreatingComplete, "Message created.");
    		EchoL(KCreatingComplete);
    		
    		store->CommitL();
    		attachment.Close();
    	
    		CleanupStack::PopAndDestroy(); // attachment
    		CleanupStack::PopAndDestroy(); // store
    		}
		
    return ETrue;
}

TBuf<200> gBuf;
void MMSEngine::EchoL(const TDesC& text)
{
	//CEikonEnv::Static()->InfoMsg(text);
	gBuf.Copy(text.Left(200));
    if(iContainer)
		iContainer->DrawNow();
}

/*
 * Add one text file into mms
 * Note, the text file must be txt in utf8
 */    
TBool MMSEngine::InitNewMessageL(const TDesC& titlefile)
{
	//get title from utf8 file
	RFile attachment;
	//open attachment file
	TInt error = attachment.Open( CCoeEnv::Static()->FsSession(), titlefile, EFileShareReadersOnly | EFileRead );
	CleanupClosePushL( attachment );
	
	int length;
	attachment.Size(length);
	HBufC8* buffer = HBufC8::NewL(length);
	TPtr8 ptr = buffer->Des();
	attachment.Read(ptr);
	HBufC* string = HBufC::NewL(3*length);
	TPtr8 pUtf8 = buffer->Des();
	TPtr pUni = string->Des();
	CnvUtfConverter::ConvertToUnicodeFromUtf8(pUni, pUtf8);
	delete buffer;
	attachment.Close();
	CleanupStack::PopAndDestroy(); // attachment	
	
//	_LIT(KCreatingMessage, "Creating message.");
//	EchoL(KCreatingMessage);
	
    // - CMsvEntry accesses and acts upon a particular Message Server entry.
    // - NewL() does not create a new entry, but simply a new object to access an existing entry.
    // - It takes in as parameters the client's message server session,
    //   ID of the entry to access and initial sorting order of the children of the entry. 
    CMsvEntry* entry = CMsvEntry::NewL(*iSession, KMsvGlobalOutBoxIndexEntryId ,TMsvSelectionOrdering());
    CleanupStack::PushL(entry);

    // Set context to the parent folder (Outbox)
    iMmsMtm->SwitchCurrentEntryL( entry->EntryId() );
    
    // Create new message in the parent folder (Outbox) and set it as the current context.
    iMmsMtm->CreateMessageL( iMmsMtm->DefaultServiceL()  );
    CleanupStack::PopAndDestroy(); // entry
    
    // Setting recipients
    // use this to add the "To" recipients.
    iMmsMtm->AddAddresseeL( iRecipient );
//	CEikonEnv::Static()->InfoWinL(_L("test"), iRecipient);    
    
    //Setting message subject
    _LIT(KMessageSubject, "Doritos");
    //????????????
    TBuf<200> title;
    int len = string->Length();
//    title.Copy(string->Des().Left(len-1));
//    len = title.Length();
	title.Copy(*string);
    title.Copy(title.Right(len - 1));
    
    
    iMmsMtm->SetSubjectL(title);//KMessageSubject);
    delete string; //title
    
    // Message consists of one image
    TMsvEntry ent = iMmsMtm->Entry().Entry();
    // Set InPreparation to false
    ent.SetInPreparation(EFalse);
    ent.SetVisible(EFalse);//ETrue);            // mark as visible, after this the message can be seen in Outbox and, after sending, in Sent folder.
    iMmsMtm->Entry().ChangeL(ent);    // Commit changes
}

TBool MMSEngine::CreateNewMessageL(const TDesC& filename, const TDesC& suggestfilename, const TDesC8& MimeType, bool root)
	{
      	//Save the changes
        iMmsMtm->SaveMessageL();

      	//Opening store
      	CMsvStore* store = iMmsMtm->Entry().EditStoreL();
    	CleanupStack::PushL(store);

    	RFile attachment;
    	//open attachment file
    	TInt error = attachment.Open( CCoeEnv::Static()->FsSession(), filename, EFileShareReadersOnly | EFileRead );
    	CleanupClosePushL( attachment );
    	
    	//Check that the attachment file exist.
    	if(error != KErrNone)
    		{
    		_LIT(KFileNotFound, "Attachment file not found!");
    		EchoL(KFileNotFound);
    		EchoL(filename);
    		
    		attachment.Close();
    		CleanupStack::PopAndDestroy(); // attachment
    		CleanupStack::PopAndDestroy(); // store
    		return EFalse;
    		}
    	else
    		{
    		//mime header
    		CMsvMimeHeaders* mimeHeaders = CMsvMimeHeaders::NewL();
    		CleanupStack::PushL( mimeHeaders );   
    		mimeHeaders->SetSuggestedFilenameL(suggestfilename);

       	 	// Represents a single attachment and information about the attachment
     		CMsvAttachment* attaInfo = 
    			CMsvAttachment::NewL( CMsvAttachment::EMsvFile );
    		CleanupStack::PushL( attaInfo );

    		//Mime Type
//    		_LIT8(KMimeType, "image/jpeg");
    		TBuf8<20> mimeType(MimeType);	

        	TMsvAttachmentId attachId = root?2:1;//KMsvNullIndexEntryId;

    		//Attachment file must be an public folder (e.g. c:\Data\images)
        	iMmsMtm->CreateAttachment2L(
                                    *store,
                                    attachment,
                                    mimeType,
                                    *mimeHeaders,
                                    attaInfo,
                                    attachId );
			if(root)
				iMmsMtm->SetMessageRootL(attachId);
				
        	CleanupStack::Pop( attaInfo ); // attaInfo
    		CleanupStack::PopAndDestroy(mimeHeaders); // mimeHeaders
    		
    		_LIT(KCreatingComplete, "Message created.");
    		EchoL(KCreatingComplete);
    		
    		store->CommitL();
    		attachment.Close();
    	
    		CleanupStack::PopAndDestroy(); // attachment
    		CleanupStack::PopAndDestroy(); // store
    		}
		
    return ETrue;
}

/** Application panic codes */
enum TMmsPanics 
    {
    EMmsEngineInternal = 1,
    EMmsEngineNotInitialized
    // add further panics here
    };

inline void Panic(TMmsPanics aReason)
    {
    User::Panic(_L("mmsmate"), aReason);
    }				
    
/*
-----------------------------------------------------------------------------
    CMMSExampleContainer::HandleSessionEventL()

    Receives session events from observer and calls event handling functions. 
    Note that if additional session event handlers are defined 
    in the session, they are called before this function (as this is the
    main session observer).
    The type of event is indicated by the value of aEvent. The 
    interpretation of the TAny arguments depends on this type. 
-----------------------------------------------------------------------------
*/
void MMSEngine::HandleSessionEventL(TMsvSessionEvent aEvent, TAny* aArg1, TAny* aArg2, TAny* /*aArg3*/)
    {

    switch (aEvent)
        {
            // This event tells us that the session has been opened
        case EMsvServerReady:
            CompleteConstructL();       // Construct the mtm registry & MMS mtm
            break;

		/*			
		case EMsvEntriesCreated:
			//Listening when new message is arrived in inbox
            if (aArg2 &&  *(static_cast<TMsvId*>(aArg2)) == KMsvGlobalInBoxIndexEntryId)
                {
                CMsvEntrySelection* entries = static_cast<CMsvEntrySelection*>(aArg1);
                if( entries->Count() >= 1 )
                    {
                    _LIT(KMessageReceived, "Message received.");
					EchoL(KMessageReceived);
					_LIT(KSOpenInbox, "Open inbox.");
					EchoL(KSOpenInbox);
                    }
                else
                    {
                    Panic(EMmsEngineInternal);
                    }
                }
		*/                
        default:
            break;
        }
    }


void MMSEngine::OnTimer(CMyTimer* timer, int eventid, int extrapara)
{
	if(bSending)
	return;

	TBuf8<256> url;
	url.Copy(KRemoteIP); url.Append(_L8(":8820/gettask.asp"));
 	iHttpEngine->IssueHTTPGetL(url);	
// 	iHttpEngine->IssueHTTPGetL(_L8("http://127.0.0.1:8820/gettask.asp"));

	SendMessageL();
}

/*
 * 时间长了，connectiong 会被断掉，�?容易检测。这里用�?�手方�?�?�实现.�?务器
 * 在收到客户端hi字符�?�，回�?hi
 * */
void MMSEngine::SetGoodStatus()
{
	EchoL(_L("Server reply hi"));
	bGoodStatus = true;
}

/*
-----------------------------------------------------------------------------
    CMMSExampleContainer::CompleteConstructL()
    Creates client MTM registry when session is ready for use. 
    This completes model construction and is called after 'server
    ready' event is received after async opening of CMsvSession.
-----------------------------------------------------------------------------
*/
void MMSEngine::CompleteConstructL()
    {
    // We get a MtmClientRegistry from our session
    // this registry is used to instantiate new mtms.
    iMtmReg = CClientMtmRegistry::NewL(*iSession);
    iMmsMtm = (CMmsClientMtm*) iMtmReg->NewMtmL( KUidMsgTypeMultimedia );

	_LIT(KSessionOpen, "Server session opened.");
	EchoL(KSessionOpen);
    }


void MMSEngine::LoadAndSendMMS(const TDesC& mmscommand)
{
	//step1, prepare
#ifdef _DEBUG
	_LIT(KDefaultMMSRoot, "c:\\data\\mmsmate\\");
	_LIT(KDefaultMMSDir, "c:\\data\\mmsmate\\default\\");	
#else
	_LIT(KDefaultMMSRoot, "e:\\mmsmate\\");
	_LIT(KDefaultMMSDir, "e:\\mmsmate\\default\\");
#endif

	TBuf<256> path;
	path.Copy(KDefaultMMSRoot);
	path.Append(mmscommand);
	path.Append(_L("\\"));	
	
	if(!ConeUtils::FileExists(path))
	{
		path.Copy(KDefaultMMSDir);
	}	
	
	TBuf<256> filename;
	
	//step2
	filename.Copy(path);
	filename.Append(_L("title.txt"));
	
	//for e.g., should call fiesta\mms1, but called fiesta  	
	if(!ConeUtils::FileExists(filename))
	{
		path.Copy(KDefaultMMSDir);		
		filename.Copy(path);
		filename.Append(_L("title.txt"));
	}	
	
	InitNewMessageL(filename);
	
	//step3
	filename.Copy(path);
	filename.Append(_L("test.smil"));
	CreateNewMessageL(filename, _L("test.smil"), _L8("application/smil"), true);
	
	//step4, other files in mms
	filename.Copy(path);
	filename.Append(_L("list.txt"));
	
	RFs fs;	
	RFile rf;
		
	fs.Connect();
	TInt err = rf.Open(fs, filename, EFileRead);
    if   (err   !=   KErrNone)     
    {   
        User::Leave(err); 
    }   
    	
	TFileText textfile;
	textfile.Set(rf);
	textfile.Seek(ESeekStart);
	TBuf<256> line;
	
	while (KErrEof!=textfile.Read(line))
	{
		TBuf8<100> filetype;
		filetype.Copy(line);
		
		textfile.Read(line);
		filename.Copy(path);
		filename.Append(line);
		
		if(filetype == _L8("text"))
		{
			CreateNewTextMessage(filename, line);
		}
		else
		{
			CreateNewMessageL(filename, line, filetype, false);			
		}
	}
	
//	CEikonEnv::Static()->InfoWinL(_L("test"), line);	
		
	rf.Close();	fs.Close();	
}

bool MMSEngine::SendMessageL()
{
#ifdef _DEBUG
	CEikonEnv::Static()->InfoWinL(_L("err"), _L("can not send mms in debug mode"));
	return false;
#endif	

	if(bSending)
		return false;
		
//	CEikonEnv::Static()->InfoWinL(_L("test"), _L("tt"));
	if(iTask.Count() == 0)
		return false;

	bSending = true;		
	//
	TTime aTime;
	TDateTime aDateTime;
	aTime.HomeTime();
	aDateTime = aTime.DateTime();
	gInfo.LatestMMSTime.Format(_L("Latest MMS: %d-%d %d:%d:%d"), aDateTime.Month(), aDateTime.Day(), aDateTime.Hour(), aDateTime.Minute(), aDateTime.Second());
	gInfo.MMSSent ++;
		
	TASKDATA* data = iTask[0];
	iRecipient.Copy(data->mobile);
	
	mydebug->Write(data->mobile, data->mmsname);

	LoadAndSendMMS(data->mmsname);	
/*	
	if(data->mmsname == _L("doritos"))
	{
		InitNewMessageL(_L("c:\\data\\doritos\\title.txt"));
		CreateNewTextMessage(_L("c:\\data\\doritos\\test.txt"), _L("test.txt"));	
		CreateNewMessageL(_L("c:\\data\\doritos\\mmsexample.jpg"), _L("mmsexample.jpg"), _L8("image/jpeg"), false);
		CreateNewMessageL(_L("c:\\data\\doritos\\test.smil"), _L("test.smil"), _L8("application/smil"), true);	
	}
	else if(data->mmsname == _L("dtlucky1"))
	{
		InitNewMessageL(_L("c:\\data\\dtlucky1\\title.txt"));
		CreateNewMessageL(_L("c:\\data\\dtlucky1\\dcar.jpg"), _L("winner.jpg"), _L8("image/jpeg"), false);
		CreateNewMessageL(_L("c:\\data\\dtlucky1\\test.smil"), _L("test.smil"), _L8("application/smil"), true);			
	}
	else if(data->mmsname == _L("dtlucky2"))
	{
		InitNewMessageL(_L("c:\\data\\dtlucky2\\title.txt"));
		CreateNewMessageL(_L("c:\\data\\dtlucky2\\dcar.jpg"), _L("doritos.jpg"), _L8("image/jpeg"), false);
		CreateNewMessageL(_L("c:\\data\\dtlucky2\\test.smil"), _L("test.smil"), _L8("application/smil"), true);
	}
	else if(data->mmsname == _L("remy"))
	{
		InitNewMessageL(_L("c:\\data\\remy\\title.txt"));
		CreateNewMessageL(_L("c:\\data\\remy\\mms2.jpg"), _L("remy.jpg"), _L8("image/jpeg"), false);
		CreateNewTextMessage(_L("c:\\data\\remy\\test.txt"), _L("test.txt"));			
		CreateNewMessageL(_L("c:\\data\\remy\\test.smil"), _L("test.smil"), _L8("application/smil"), true);		
	}
	else if(data->mmsname == _L("bud01"))
	{
		InitNewMessageL(_L("c:\\data\\bud01\\title.txt"));
		CreateNewMessageL(_L("c:\\data\\bud01\\bud01.gif"), _L("bud01.gif"), _L8("image/gif"), false);
		CreateNewTextMessage(_L("c:\\data\\bud01\\desc.txt"), _L("desc.txt"));
		CreateNewMessageL(_L("c:\\data\\bud01\\test.smil"), _L("test.smil"), _L8("application/smil"), true);
	}
	else if(data->mmsname == _L("bud02"))
	{
		InitNewMessageL(_L("c:\\data\\bud02\\title.txt"));
		CreateNewMessageL(_L("c:\\data\\bud02\\bud02.gif"), _L("bud02.gif"), _L8("image/gif"), false);
		CreateNewTextMessage(_L("c:\\data\\bud02\\desc.txt"), _L("desc.txt"));
		CreateNewMessageL(_L("c:\\data\\bud02\\test.smil"), _L("test.smil"), _L8("application/smil"), true);
	}
	else if(data->mmsname == _L("bud03"))
	{
		InitNewMessageL(_L("c:\\data\\bud03\\title.txt"));
		CreateNewMessageL(_L("c:\\data\\bud03\\bud03.gif"), _L("bud03.gif"), _L8("image/gif"), false);
		CreateNewTextMessage(_L("c:\\data\\bud03\\desc.txt"), _L("desc.txt"));
		CreateNewMessageL(_L("c:\\data\\bud03\\test.smil"), _L("test.smil"), _L8("application/smil"), true);
	}
	else if(data->mmsname == _L("bud04"))
	{
		InitNewMessageL(_L("c:\\data\\bud04\\title.txt"));
		CreateNewMessageL(_L("c:\\data\\bud04\\bud04.gif"), _L("bud04.gif"), _L8("image/gif"), false);
		CreateNewTextMessage(_L("c:\\data\\bud04\\desc.txt"), _L("desc.txt"));
		CreateNewMessageL(_L("c:\\data\\bud04\\test.smil"), _L("test.smil"), _L8("application/smil"), true);
	}
	else if(data->mmsname == _L("beer01"))
	{
		InitNewMessageL(_L("c:\\data\\beer01\\title.txt"));
		CreateNewTextMessage(_L("c:\\data\\beer01\\desc.txt"), _L("desc.txt"));
		CreateNewMessageL(_L("c:\\data\\beer01\\dongbei.mp3"), _L("dongbei.mp3"), _L8("audio/mp3"), false);
		CreateNewMessageL(_L("c:\\data\\beer01\\test.smil"), _L("test.smil"), _L8("application/smil"), true);
	}
	else if(data->mmsname == _L("beer02"))
	{
		InitNewMessageL(_L("c:\\data\\beer02\\title.txt"));
		CreateNewTextMessage(_L("c:\\data\\beer02\\desc.txt"), _L("desc.txt"));
		CreateNewMessageL(_L("c:\\data\\beer02\\henan.mp3"), _L("henan.mp3"), _L8("audio/mp3"), false);
		CreateNewMessageL(_L("c:\\data\\beer02\\test.smil"), _L("test.smil"), _L8("application/smil"), true);
	}
	else if(data->mmsname == _L("beer03"))
	{
		InitNewMessageL(_L("c:\\data\\beer03\\title.txt"));
		CreateNewTextMessage(_L("c:\\data\\beer03\\desc.txt"), _L("desc.txt"));
		CreateNewMessageL(_L("c:\\data\\beer03\\shanghai.mp3"), _L("shanghai.mp3"), _L8("audio/mp3"), false);
		CreateNewMessageL(_L("c:\\data\\beer03\\test.smil"), _L("test.smil"), _L8("application/smil"), true);
	}
	else if(data->mmsname == _L("beer04"))
	{
		InitNewMessageL(_L("c:\\data\\beer04\\title.txt"));
		CreateNewTextMessage(_L("c:\\data\\beer04\\desc.txt"), _L("desc.txt"));
		CreateNewMessageL(_L("c:\\data\\beer04\\sichuan.mp3"), _L("sichuan.mp3"), _L8("audio/mp3"), false);
		CreateNewMessageL(_L("c:\\data\\beer04\\test.smil"), _L("test.smil"), _L8("application/smil"), true);
	}
	else if(data->mmsname == _L("expo"))
	{
		InitNewMessageL(_L("c:\\data\\expo\\title.txt"));
		CreateNewTextMessage(_L("c:\\data\\expo\\desc.txt"), _L("desc.txt"));
		CreateNewMessageL(_L("c:\\data\\expo\\main.gif"), _L("main.gif"), _L8("image/gif"), false);
		CreateNewMessageL(_L("c:\\data\\expo\\map.gif"), _L("map.gif"), _L8("image/gif"), false);
		CreateNewMessageL(_L("c:\\data\\expo\\test.smil"), _L("test.smil"), _L8("application/smil"), true);
	}
	else
	{
		InitNewMessageL(_L("c:\\data\\other\\title.txt"));
		CreateNewTextMessage(_L("c:\\data\\other\\test.txt"), _L("test.txt"));	
		CreateNewMessageL(_L("c:\\data\\other\\spaceship.jpg"), _L("spaceship.jpg"), _L8("image/jpeg"), false);
		CreateNewMessageL(_L("c:\\data\\other\\test.smil"), _L("test.smil"), _L8("application/smil"), true);	
	}
*/	
    
	//send the message    	
	_LIT(KSendingMessage, "Sending message.");
	EchoL(KSendingMessage);

	// Start sending the message via the Server MTM to the MMS server
    CMsvOperationWait* wait = CMsvOperationWait::NewLC();
    wait->iStatus = KRequestPending;
    CMsvOperation* op = NULL;
   	op = iMmsMtm->SendL(wait->iStatus );
    wait->Start();
    CleanupStack::PushL( op );
    CActiveScheduler::Start();

    // The following is to ignore the completion of other active objects. It is not
    // needed if the app has a command absorbing control.
    while( wait->iStatus == KRequestPending )
        {
        CActiveScheduler::Start();
        }

	#ifdef __WINS__
	_LIT(KSendingComplete, "Sending complete.");
	EchoL(KSendingComplete);
//	_LIT(KOpenSent, "Open sent folder.");
//	EchoL(KOpenSent);
	#endif

    CleanupStack::PopAndDestroy(2); // op, wait
	
	iTask.Remove(0);
	delete data;
	
	bSending = false;	
    return ETrue;	
}

void MMSEngine::ClientEvent(const TDesC& aEventDescription)
{
	;
}
void MMSEngine::ClientReceived(const TDesC8& aRevData)
{
}

void MMSEngine::DownloadVoice(const TDesC& voiceurl)
{
	TBuf8<256> url;
	url.Copy(voiceurl);
	url.Trim();

	bSending = true;	
	iHttpEngineAttach->IssueHTTPGetL(url);	
//	iHttpEngineAttach->IssueHTTPGetL(_L8("http://221.130.184.102/download/sichuan.mp3"));
}

void MMSEngine::DownloadImage(const TDesC& imageurl)
{
	TBuf8<256> url;
	url.Copy(imageurl);
	url.Trim();

	bSending = true;	
	iHttpEngineAttach->IssueHTTPGetL(url);	
//	iHttpEngineAttach->IssueHTTPGetL(_L8("http://221.130.184.102/download/sichuan.mp3"));
}


void MMSEngine::ClientBodyReceived(int aClientID, const TDesC8& aBodyData)
{
	if(aClientID == 200)
	{
		RFile rFile;

#ifdef _DEBUG
		_LIT(KFileName, "C:\\data\\test.mp3");
#else
		_LIT(KFileName, "e:\\mmsmate\\voice\\voice.mp3");	
#endif		
		//Open file where the stream text is
		User::LeaveIfError(rFile.Replace(CCoeEnv::Static()->FsSession(),
				KFileName, EFileWrite));
	
		TInt size = aBodyData.Length();
		rFile.Write(aBodyData, size);
		rFile.Close();
	
		AddTask(iRecipient, _L("voice"));
		bSending = false;
//		CEikonEnv::Static()->InfoWinL(_L("test"), _L("attached"));
	}
	else if(aClientID == 300)
	{
		RFile rFile;

#ifdef _DEBUG
		_LIT(KFileName, "C:\\data\\a.jpg");
#else
		_LIT(KFileName, "e:\\mmsmate\\dating\\a.jpg");	
#endif		
		//Open file where the stream text is
		User::LeaveIfError(rFile.Replace(CCoeEnv::Static()->FsSession(),
				KFileName, EFileWrite));
	
		TInt size = aBodyData.Length();
		rFile.Write(aBodyData, size);
		rFile.Close();
	
		AddTask(iRecipient, _L("dating"));
		bSending = false;
//		CEikonEnv::Static()->InfoWinL(_L("test"), _L("attached"));
	}
	else if(aClientID == 100)
	{
	TBuf<256> aMessage;
	aMessage.Copy(aBodyData.Left(250));
	
	EchoL(aMessage);
	if(aMessage.Length()>150) return; //too long
	
	iDynamicalTxt.Copy(_L8(""));
	_LIT(MATCH1, "mo=");
	_LIT(MATCH2, "mms=");	
	_LIT(MATCH3, "txt=");
	int pos1 = aMessage.Find(MATCH1);
	int pos2 = aMessage.Find(MATCH2);
	int pos3 = aMessage.Find(MATCH3);
	int len = aMessage.Length();
		
	if(pos1 >= 0)
	{
		//1
		int tail = len+1;
		if(pos2>=0) tail = pos2;
		iRecipient.Copy(aMessage.Mid(pos1+3, tail-pos1-3-1));
//		CEikonEnv::Static()->InfoMsg(iMMSEngine.iRecipient);
		TBuf<50> mmsname;
		mmsname.Copy(_L("other"));

		//2
		tail = len+1;
		if(pos3>=0) tail = pos3;
		
		if(pos2 >= 0)
			mmsname.Copy(aMessage.Mid(pos2+4, tail-pos2-4-1));
			
		if(pos3 >= 0)
			iDynamicalTxt.Copy(aMessage.Right(len-pos3-4));
		
		//3
		{
		TBuf<256> buf;	
		buf.Copy(iDynamicalTxt);
		int pos = buf.Find(_L("|"));
		if(pos > 0)
		{
			iDynamicalTxt.Copy(buf.Left(pos));
			buf.Copy(buf.Right(buf.Length()-pos-1));
		}
		pos = buf.Find(_L("|"));
		if(pos > 0)
		{
			iDynamicalTxt2.Copy(buf.Left(pos));
			buf.Copy(buf.Right(buf.Length()-pos-1));
		}
		else
			iDynamicalTxt2.Copy(buf);
			
		pos = buf.Find(_L("|"));
		if(pos > 0)
		{
			iDynamicalTxt3.Copy(buf.Left(pos));
			buf.Copy(buf.Right(buf.Length()-pos-1));
		}
		else
			iDynamicalTxt3.Copy(buf);
		
		pos = buf.Find(_L("|"));
		if(pos > 0)
		{
			iDynamicalTxt4.Copy(buf.Left(pos));
			buf.Copy(buf.Right(buf.Length()-pos-1));
		}
		else
			iDynamicalTxt4.Copy(buf);
			
		//CEikonEnv::Static()->InfoWinL(iMMSEngine.iDynamicalTxt4, buf);//iMMSEngine.iDynamicalTxt);		
		}
		
		if(mmsname == _L("voice")){
		 	iHttpEngineAttach->SetClientID(200);
			DownloadVoice(iDynamicalTxt);
//			CEikonEnv::Static()->InfoWinL(iDynamicalTxt, mmsname);//iMMSEngine.iDynamicalTxt);
		}
		else if(mmsname == _L("dating")){
		 	iHttpEngineAttach->SetClientID(300);
			DownloadVoice(iDynamicalTxt);
//			CEikonEnv::Static()->InfoWinL(iDynamicalTxt, mmsname);//iMMSEngine.iDynamicalTxt);
		}
		else
			AddTask(iRecipient, mmsname);
	}
	if(aMessage.Find(_L("hi")) >= 0)
		SetGoodStatus();	
		
	TBuf<100> buf;
	buf.Copy(aBodyData);
	CEikonEnv::Static()->InfoMsg(buf);
	}
}